package com.AdvancedDemos.Learn网络编程.CS架构.useTCP4多线程实现一个服务端多个客户端;

import java.io.DataInputStream;
import java.io.InputStream;
import java.net.Socket;

//服务器端处理socket的线程
public class ServerSocketThread extends Thread {
    //定义成员变量，将每个线程对象与每个socket绑定
    private Socket thisSocket;

    public ServerSocketThread(Socket thisSocket) {
        this.thisSocket = thisSocket;
    }

    @Override
    public void run() {
        System.out.println("【服务器端】一个新socket开始接收数据！");

        try {
            //接收数据
            //获取输入流
            InputStream inputStream = thisSocket.getInputStream();
            DataInputStream dis = new DataInputStream(inputStream);//收发要对应,都使用Data(In/Out)putStream
            while (true) {

                String data = dis.readUTF();
                System.out.println(data);
                System.out.println(thisSocket.getRemoteSocketAddress());
                //判断数据是否为结束信号，如果为结束信号，则跳出循环
                if ("#exit".equals(data)) break;
            }
            //关闭资源
            dis.close();
            //socket.close();
            System.out.println("有人下线了：" + thisSocket.getRemoteSocketAddress());
        } catch (Exception e) {
            System.out.println(thisSocket.getRemoteSocketAddress() + "出现了异常，该用户下线了！");
        }
    }

}
